package com.longyiqun.jinjin.upload;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 * program: upload
 * package: com.longyiqun.jinjin.upload
 * author: 龙轶群
 * create: 2018-05-12 13:39
 **/

@RestController
@RequestMapping("/upload")
public class UploadRestControllerImpl {

    private static Logger log = LoggerFactory.getLogger(UploadRestControllerImpl.class);


    @RequestMapping(value = "/", method = RequestMethod.POST)
    public String upload(MultipartFile file, HttpServletRequest request) {

        String path = "";

        log.debug("开始...");

        try {
            //存服务器
            //如果文件不为空，写入上传路径
            if (!file.isEmpty()) {
                //上传文件路径
                path = request.getServletContext().getRealPath("/upload/");
                //上传文件名
                String filename = file.getOriginalFilename();
                File filepath = new File(path, filename);
                //判断路径是否存在，如果不存在就创建一个
                if (!filepath.getParentFile().exists()) {
                    filepath.getParentFile().mkdirs();
                }
                //将上传文件保存到一个目标文件当中
                file.transferTo(new File(path + File.separator + filename));

            }


            //构造一个带指定Zone对象的配置类
            Configuration cfg = new Configuration(Zone.zone0());
            //...其他参数参考类注释
            UploadManager uploadManager = new UploadManager(cfg);
            //...生成上传凭证，然后准备上传
            String accessKey = "I9rORYS7ghuHyfrIk9iPj2W6FKmGElXgm5OuHUMp";
            String secretKey = "-zcTu6iZzkrSJl1neCBFgCT_t3AFKWdB9HiFasyg";
            String bucket = "jinjin";

            String localFilePath = path + file.getOriginalFilename();
            //默认不指定key的情况下，以文件内容的hash值作为文件名
            String key = null;
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            log.debug("upToken: " + upToken);
            try {
                Response response = uploadManager.put(localFilePath, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                log.info(putRet.key);
                log.error(putRet.hash);

                return "{\n" +
                        "  \"code\": 0\n" +
                        "  ,\"msg\": \"\"\n" +
                        "  ,\"data\": {\n" +
                        "    \"src\": " + "\"http://p8e1kn64a.bkt.clouddn.com/" + putRet.key + "\"\n" +
                        "  }\n" +
                        "}       \n";

            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {

                }
                return ex.error();
            }

        } catch (Exception ex) {
            return ex.getMessage();
        }
    }
}
